import { useEffect, useState } from 'react'
import './index.scss'
import axios from '../../api/index'
import { useNavigate, useLocation } from 'react-router-dom'
import { SearchOutlined } from '@ant-design/icons'
import { PullToRefresh } from 'antd-mobile'
import Nabbar from '../../extract/index'
import dayjs from 'dayjs'

type Department = { id: number; departmentName: string }
type SickCircleItem = { 
  sickCircleId: number; 
  title: string; 
  releaseTime: string; 
  detail: string; 
  collectionNum: number; 
  commentNum: number;
  departmentId?: number;
  mainSymptom?: string;
  hospitalName?: string;
  startTime?: string;
  endTime?: string;
  treatmentProcess?: string;
}

function Byq() {
   const navigate = useNavigate()
   const location = useLocation()
   const [data, setData] = useState<Department[]>([])
   const [departmentId, setDepartmentId] = useState(0)
   const [page] = useState(1)
   const [count] = useState(10)
   const [title, setTitle] = useState<SickCircleItem[]>([])
   const [refreshKey, setRefreshKey] = useState(0)
   useEffect(() => {
      axios.get('/share/knowledgeBase/v1/findDepartment').then(res => {
         const list = res?.data?.result || []
         setData(list)
         // 默认内科
         const neike = list.find((item: Department) => item?.departmentName === '内科')
         console.log('找到的内科科室:', neike)
         if (neike?.id) {
            setDepartmentId(neike.id)
            console.log('设置内科科室ID:', neike.id)
         } else if (list.length > 0) {
            setDepartmentId(list[0].id)
            console.log('设置默认科室ID:', list[0].id)
         }
      })
   }, [])
   // 获取病友圈列表
   useEffect(() => {
      if (departmentId === 0) return; // 如果还没有选择科室，不请求数据
      
      axios.get('/user/sickCircle/v1/findSickCircleList', {
         params: {
            departmentId: departmentId,
            page: page,
            count: count
         }
      }).then(res => {
         console.log(res);
         const apiData = res.data.result || []
         
         // 获取用户发布的帖子
         const publishedPosts = JSON.parse(localStorage.getItem('publishedPosts') || '[]')
         console.log('用户发布的帖子:', publishedPosts)
         console.log('当前科室ID:', departmentId)
         
         // 过滤出当前科室的发布帖子
         const currentDepartmentPosts = publishedPosts.filter((post: SickCircleItem) => {
            console.log('检查帖子:', post.title, '科室ID:', post.departmentId, '匹配:', post.departmentId === departmentId)
            return post.departmentId === departmentId
         })
         console.log('当前科室的发布帖子:', currentDepartmentPosts)
         
         // 将当前科室的发布帖子添加到API数据前面
         const allData = [...currentDepartmentPosts, ...apiData]
         
         setTitle(allData)
      }).catch(error => {
         console.error('获取病友圈列表失败:', error)
         // 如果API失败，只显示当前科室的用户发布帖子
         const publishedPosts = JSON.parse(localStorage.getItem('publishedPosts') || '[]')
         const currentDepartmentPosts = publishedPosts.filter((post: SickCircleItem) => 
            post.departmentId === departmentId
         )
         setTitle(currentDepartmentPosts)
      })
   }, [departmentId, page, count, refreshKey])

   // 监听页面变化，当从fbbyq页面跳转过来时刷新数据
   useEffect(() => {
      if (location.state?.from === 'fbbyq') {
         console.log('从fbbyq页面跳转过来，刷新数据')
         setRefreshKey(prev => prev + 1)
      }
   }, [location.state])

   // 下拉刷新处理函数
   const onRefresh = async () => {
      try {
         // 重新获取数据
         const res = await axios.get('/user/sickCircle/v1/findSickCircleList', {
            params: {
               departmentId: departmentId,
               page: page,
               count: count
            }
         })
         
         const apiData = res.data.result || []
         
         // 获取用户发布的帖子
         const publishedPosts = JSON.parse(localStorage.getItem('publishedPosts') || '[]')
         
         // 过滤出当前科室的发布帖子
         const currentDepartmentPosts = publishedPosts.filter((post: SickCircleItem) => 
            post.departmentId === departmentId
         )
         
         // 将当前科室的发布帖子添加到API数据前面
         const allData = [...currentDepartmentPosts, ...apiData]
         
         setTitle(allData)
         console.log('下拉刷新成功')
      } catch (error) {
         console.error('下拉刷新失败:', error)
         // 如果API失败，只显示当前科室的用户发布帖子
         const publishedPosts = JSON.parse(localStorage.getItem('publishedPosts') || '[]')
         const currentDepartmentPosts = publishedPosts.filter((post: SickCircleItem) => 
            post.departmentId === departmentId
         )
         setTitle(currentDepartmentPosts)
      }
   }
   return (
      <div className='byq'>
         <div className='byq-nav'>
            <Nabbar></Nabbar>
         </div>
         {/* 自定义tabbar */}
         <div className='custom-tabbar'>
            <div className='tabbar-content'>
               {data.map((item) => (
                  <div 
                     key={item.id} 
                     className={`tab-item ${departmentId === item.id ? 'active' : ''}`}
                     onClick={() => setDepartmentId(item.id)}
                  >
                     {item.departmentName}
                  </div>
               ))}
            </div>
            <div className='tabbar-divider'></div>
            <div className='search-icon' onClick={() => navigate('/byqss')}>
               <SearchOutlined />
            </div>
         </div>
         {/* 列表数据 */}
         <div className='byq-content'>
            <PullToRefresh
               onRefresh={onRefresh}
               renderText={(status) => {
                  switch (status) {
                     case 'pulling':
                        return '下拉刷新'
                     case 'canRelease':
                        return '释放刷新'
                     case 'refreshing':
                        return '正在刷新...'
                     default:
                        return '下拉刷新'
                  }
               }}
            >
               <div className='byq-list-container'>
                  {
                     title.map((item, index) => {
                        return (
                           <div key={index} className='byq-list' onClick={() => navigate(`/byqxq/${item.sickCircleId}`)}>
                              <p className='list'>{item.title}</p>
                              <p className='sj'>{dayjs(item.releaseTime).format('YYYY-MM-DD hh:mm:ss')}</p>
                              <p className='list-item'>{item.detail}</p>
                              <p className='scjy'>
                                 <span>收藏 {item.collectionNum}</span>
                                 <span className='jy'>建议 {item.commentNum}</span>
                              </p>
                           </div>
                        )
                     })
                  }
               </div>
            </PullToRefresh>
         </div>

      </div>
   )
}

export default Byq